package com.huiminpay.merchant.common.intercept;

import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.ErrorCode;
import com.huiminpay.common.cache.domain.RestErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class GlobalExceptionHandler {
    //处理异常
    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse handlerException(HttpServletRequest httpServletRequest,
                                              HttpServletResponse httpServletResponse,
                                              Exception e){
    if (e instanceof BusinessException){
        //根据异常类型,指定不同处理方案
        BusinessException businessException = (BusinessException) e;
        ErrorCode errorCode = businessException.getErrorCode();
        //可预知异常代码
        int code = errorCode.getCode();
        //可预知异常对象
        String desc = errorCode.getDesc();
        //组装对象返回
        return new RestErrorResponse(String.valueOf(code),desc);

    }
        //不可预知异常
    return new RestErrorResponse(String.valueOf(CommonErrorCode.UNKNOWN.getCode()),
        CommonErrorCode.UNKNOWN.getDesc());
    }

}
